package Top_Interview_Questions_Review._004Binary_Search;

/**
 * @Author: 吕庆龙
 * @Date: 2020/3/14 20:13
 * <p>
 * https://leetcode-cn.com/problems/search-in-rotated-sorted-array/solution/ji-bai-liao-9983de-javayong-hu-by-reedfan/
 *
 */
public class _0033 {

    public static void main(String[] args) {
        _0033 test = new _0033();
        int[] nums = {4,5,6,7,0,1,2};
        int[] nums1 = {8,9,1,2,3,4,5,6,7};
        test.search(nums1,2);
    }

    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int start = 0;
        int end = nums.length - 1;
        int mid;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            //前半部分有序,注意此处用小于等于  2 3 4 5 6 7 1
            if (nums[start] <= nums[mid]) {
                //target在前半部分
                if (target >= nums[start] && target < nums[mid]) {
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } else {  //6 7 1 2 3 4 5
                if (target <= nums[end] && target > nums[mid]) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }

        }
        return -1;

    }
}
